<?php
/**
 * BQue Description
 * @package core.lib
 * @name Output
 * @filesource Output.php
 * @author Meta Sanjaya
 */

class Output
{
    private $output;
    private $headers;

    /**
     * @access public
     * @method __construct
     * @param void
     * @return void
     */
    public function __construct()
    {
        $this->output = '';
        $this->headers = array();
        $this->addHeader('content-type', 'text/html');
        ob_start();
    }

    public function render($vars, $view, $app='', $return=false)
    {
        extract($vars);

        $app = empty($app)?System::get('uri')->getApp():$app;

        if(!(@include_once __APP__ . $app . DIRECTORY_SEPARATOR . 'view' . DIRECTORY_SEPARATOR . $view . '.php')) {
            trigger_error($app . ' doesn\'t exists');
        }

        $this->output = ob_get_contents();

        ob_end_clean();

        if(!!$return)
        {
            return $this->getOutput();
        }
        else
        {
            /*$HTTP_ACCEPT_ENCODING = $_SERVER["HTTP_ACCEPT_ENCODING"];
            $len = strlen($this->getOutput());
            if(headers_sent() || $len < 2048)
                $encoding = false;
            else if(strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false) {
                $encoding = 'x-gzip';
                $this->addHeader('content-encoding', $encoding);
            } else if(strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false) {
                $encoding = 'gzip';
                $this->addHeader('content-encoding', $encoding);
            } else
                $encoding = false;

         */
            foreach($this->headers as $name => $header)
            {
                header($name . ': ' . $header, true);
            }     

            /*if($encoding) {
                echo "\x1f\x8b\x08\x00\x00\x00\x00\x00";
                $contents = gzcompress($this->getOutput(), 9);
                echo trim(substr($contents, 0, $len));
            } else*/
                echo $this->getOutput();
        }
    }

    public function addHeader($name, $stringHeader, $replace=true)
    {
       if(isset($this->headers[$name]) && !!$replace)
       {
           $this->headers[$name] = $stringHeader;
       }
    }

    public function getOutput()
    {
        return $this->output;
    }
}